﻿using System;
using System.ServiceProcess;

namespace ConsoleApp13
{
    internal class Program
    {
        static void Main(string[] args)
        {

            string serviceName = "MySQL"; // 替换为你的服务名称

            try
            {           

                // 创建服务控制器对象
                ServiceController service = new ServiceController(serviceName);
                // 检查服务状态
                Console.WriteLine($"当前操作系统: {Environment.OSVersion}");
                Console.WriteLine($"当前平台: {Environment.OSVersion.Platform}");
                Console.WriteLine($"当前服务 {serviceName} 状态: {service.Status}");

                if (service.Status == ServiceControllerStatus.Stopped)
                {
                    Console.WriteLine("服务未启动，正在尝试启动...");
                    service.Start();
                    service.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromSeconds(30));
                    Console.WriteLine("服务已成功启动。");
                }
                else if (service.Status == ServiceControllerStatus.Running)
                {
                    Console.WriteLine("服务已在运行中，无需启动。");
                }
                else
                {
                    Console.WriteLine($"服务状态为 {service.Status}，无法处理。");
                }
            }
            catch (InvalidOperationException ex)
            {
                Console.WriteLine($"找不到服务 {serviceName}，请检查服务名称是否正确。错误: {ex.Message}");
            }
            catch (PlatformNotSupportedException ex)
            {
                Console.WriteLine($"操作系统不支持 Windows 服务操作。错误: {ex.Message}");
            }
            catch (UnauthorizedAccessException ex)
            {
                Console.WriteLine($"权限不足：无法访问服务。错误: {ex.Message}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"发生未知错误: {ex.Message}");
            }
            Console.ReadLine();
        }
    }
}
